import mongoose from 'mongoose';
import db from './db';
mongoose.Promise = global.Promise;

const CourseMsgSchema = new mongoose.Schema({
    courseId: String,
    tags: Object,
    msg: Array,
    score: Array,
    likes: Object,
});

CourseMsgSchema.methods.saveCourseMsg = function (courseMsg, cb) {
    this.model('courseMsg').insertMany([courseMsg], cb);
};

CourseMsgSchema.methods.getCourseMsgs = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const courseMsgModel = this.model('courseMsg');
    courseMsgModel.count(leftQuery, function (err, count) {
        courseMsgModel.find(leftQuery).skip((current - 1) * pageSize).limit(pageSize).exec((err, courseMsgs) => cb(err, courseMsgs, count));
    });
};

CourseMsgSchema.methods.getAllCourseMsgs = function (query, cb) {
    this.model('courseMsg').find(query, { name: 1, _id: 0 }, cb);
};

CourseMsgSchema.methods.getCourseMsg = function (query, cb) {
    this.model('courseMsg').findOne(query, cb);
};

CourseMsgSchema.methods.updateCourseMsg = function (courseMsg, cb) {
    const _id = courseMsg._id;
    delete courseMsg._id;
    this.model('courseMsg').findOneAndUpdate({ _id }, { $set: courseMsg }, cb);
};

CourseMsgSchema.methods.removeCourseMsgs = function (courseMsgIds, cb) {
    this.model('courseMsg').remove({ _id: { $in: courseMsgIds } }, cb);
};

export default db.model('courseMsg', CourseMsgSchema);